<?

require_once("Mailer.php");

class CliManager
{
	var $id_negozio;
	var $db;
	
	function CliManager($id_negozio, &$db)
	{
		$this->id_negozio = $id_negozio;
		$this->db = &$db;
	}
	
	function listCli()
	{
		$lista_clienti = array();
		$query = "SELECT * FROM moka_ecomm_".$this->id_negozio.".clienti WHERE 1 ";
		$rs = $this->db->query($query);
		while($rw = mysql_fetch_assoc($rs))
		{
			foreach($rw as $nome=>$valore) $lista_clienti[$rw[id]][$nome] = $valore;
		}
		return $lista_clienti;
	}
	
	function getCli($id_cliente)
	{
		$cliente = array();
		$query = "SELECT * FROM moka_ecomm_".$this->id_negozio.".clienti WHERE id='$id_cliente' ";
		$rs = $this->db->query($query);
		if($rw = mysql_fetch_assoc($rs))
		{
			foreach($rw as $nome=>$valore) $cliente[$nome] = $valore;
		}
		return $cliente;
	}
	
	function setCli($cliente)
	{
		$qpiece = "	nome='$cliente[nome]',
					cognome='$cliente[cognome]',
					username='$cliente[username]',
					email='$cliente[email]',";
		if($cliente[password])$qpiece .= "password='".md5($cliente[password])."',";
		$qpiece .= "indirizzo='$cliente[indirizzo]',
					citta='$cliente[citta]',
					cap='$cliente[cap]',
					provincia='$cliente[provincia]',
					nazione='$cliente[nazione]',
					telefono='$cliente[telefono]',
					cf='$cliente[cf]'
					";
		if($cliente[id_cliente]>0)
		{
			$query = "UPDATE moka_ecomm_".$this->id_negozio.".clienti SET
						$qpiece
						WHERE id='$cliente[id_cliente]' ";
			$rs = $this->db->query($query);
			$id_cliente = $cliente[id_cliente];
		}else 
		{
			$query = "SELECT * FROM moka_ecomm_".$this->id_negozio.".clienti 
						WHERE username='$cliente[username]'	";
			$rs = $this->db->query($query);
			if(mysql_num_rows($rs)==0)
			{
				$query = "INSERT INTO moka_ecomm_".$this->id_negozio.".clienti SET
							$qpiece
						 	";
				if($this->db->query($query))
				{
					$id_cliente = $this->db->lastInsertedId();
					$cliente[id] = 	$id_cliente;
					$mail = new Mailer($this->id_negozio);
					$mail->sendShopMail("registrazione", $cliente);				
				}
				
			}
		}
		
		
		return $this->getCli($id_cliente);
	}
	
	
	function isCli($username, $password)
	{
		$query = "SELECT * FROM moka_ecomm_$this->id_negozio.clienti WHERE username='$username' AND password='".md5($password)."'";
		$rs = $this->db->query($query);
		if($rw = mysql_fetch_assoc($rs))
		{
			$query = "UPDATE moka_ecomm_$this->id_negozio.clienti SET last_login=".time()." WHERE id='$rw[id]'";
			$this->db->query($query);
			return $rw;
		}
		return false;
	}
	
	function delCli($id)
	{
		$query = "SELECT * FROM moka_ecomm_$this->id_negozio.clienti WHERE id='$id'";
		$rs = $this->db->query($query);
		if($rw = mysql_fetch_assoc($rs))
		{
			$query = "DELETE FROM moka_ecomm_$this->id_negozio.clienti WHERE id='$id'";
			$this->db->query($query);
			return true;
		}
		return false;
	}
}
?>